package com.woniu.order.service.impl;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.common.dto.OrderBreakDto;
import com.woniu.common.dto.ShouhouProductDto;
import com.woniu.common.dto.UserDTO;
import com.woniu.common.entity.AddrDto;
import com.woniu.common.entity.ZyProduct;
import com.woniu.common.utils.JWTUtil;
import com.woniu.common.utils.PageParam;
import com.woniu.common.utils.ResponseData;
import com.woniu.common.utils.SnowflakeIdGenerator;
import com.woniu.order.dto.ShouhouDto;
import com.woniu.order.feign.EcssOrderFeign;
import com.woniu.order.feign.ProductFeign;
import com.woniu.order.feign.UserFeign;
import com.woniu.order.pojo.*;
import com.woniu.order.service.*;
import com.woniu.order.mapper.ZyShouhouMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author xue
 * @description 针对表【zy_shouhou】的数据库操作Service实现
 * @createDate 2024-08-09 15:42:04
 */
@Service
public class ZyShouhouServiceImpl extends ServiceImpl<ZyShouhouMapper, ZyShouhou>
        implements ZyShouhouService {
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ZyShouhouMapper shouhouMapper;
    @Autowired
    private ZyShouhoudetailService shouhoudetailService;
    @Autowired
    private LogisticsService logisticsService;
    @Autowired
    private ZyOrderService orderService;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private EcssOrderFeign ecssOrderFeign;


    @SneakyThrows
    @Override
    public ResponseData<?> addShouhou(String orderId) {
        //待发货状态的订单直接发起售后
        //String orderId = shouhou.getOid();
        Cookie[] cookies = request.getCookies();
        String jwt = null;

        ZyOrder order = orderService.getById(orderId);

        //订单优惠金额（退款金额=订单总价-订单优惠金额
        BigDecimal discountAmount = order.getDiscountAmount();
        BigDecimal tuikuanAllMoney = new BigDecimal(0);
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("jwt")) {
                jwt = cookie.getValue();
            }
        }
        Map<String, Object> user = JWTUtil.getUserInfo(jwt);
        String userId = user.get("id").toString();
        List<ZyShouhou> shouhouList = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderId).list();
        for (OrderDetail orderDetail : orderDetailList) {
            String shouhouId = String.valueOf(IdUtil.getSnowflake().nextId());
            ZyShouhou shouhou = new ZyShouhou();
            shouhou.setId(shouhouId);
            shouhou.setOid(orderId);
            shouhou.setShOdid(orderDetail.getId());
            shouhou.setShUserid(userId);

            shouhou.setShProductid(orderDetail.getProductId());
            shouhou.setProductName(orderDetail.getProductName());
            BigDecimal orderPrice = orderDetail.getProductPrice().multiply(BigDecimal.valueOf(orderDetail.getBuyNum()));
            shouhou.setOrderAllmoney(orderPrice);
            shouhou.setTuikuanMoney(orderPrice);
            shouhou.setShReason("订单未发货退款");
            shouhou.setShShtype(String.valueOf(1));
            shouhou.setShStatus(6);

            //shouhou.setFromWhere();
            //shouhou.setToWhere();
            //shouhou.setWuliuId();
            shouhou.setShCreatetime(new Date());
            //shouhou.setShRemark();
            tuikuanAllMoney = orderPrice.add(tuikuanAllMoney);
            shouhouList.add(shouhou);
        }
        //批量添加售后
        boolean b = saveBatch(shouhouList);
        List<ZyShouhoudetail> shouhoudetailList = new ArrayList<>();
        if (b) {
            //售后添加成功  开始添加售后详情
            for (ZyShouhou shouhou : shouhouList) {
                String shouhouDetailId = String.valueOf(IdUtil.getSnowflake().nextId());
                String shouhouId = shouhou.getId();
                ZyShouhoudetail zyShouhoudetail = new ZyShouhoudetail();
                zyShouhoudetail.setId(shouhouDetailId);
                zyShouhoudetail.setShdShid(shouhouId);
                zyShouhoudetail.setShdShtype("1");
                zyShouhoudetail.setShdProductid(shouhou.getShProductid());
                zyShouhoudetail.setShdName(shouhou.getProductName());
                String orderDetailId = shouhou.getShOdid();
                OrderDetail orderDetail = orderDetailService.getById(orderDetailId);
                Integer buyNum = orderDetail.getBuyNum();
                zyShouhoudetail.setShdThnum(buyNum);
                zyShouhoudetail.setShdThprice(shouhou.getTuikuanMoney());
                zyShouhoudetail.setShdRemarks("订单未发货申请售后，仅退款");
                //zyShouhoudetail.setShdThpz();
                zyShouhoudetail.setShdThsubmittime(new Date());

                shouhoudetailList.add(zyShouhoudetail);

            }
            boolean aaa = shouhoudetailService.saveBatch(shouhoudetailList);
            if (aaa) {
                //售后和售后详情都已生成下一步
                // 1.退款（给用户的余额加上退款的钱，用户总消费减去优惠前的钱
                // 2.加商品库存
                // 3.订单状态改成5已取消,两个订单的状态都要改

                // 1.退款（给用户的余额加上退款的钱，用户总消费减去优惠前的钱
                UserDTO userDTO = userFeign.queryUserById(userId).getData();
                String userPurse = userDTO.getUserPurse();
                BigDecimal userPurse1 = new BigDecimal(userPurse);
                BigDecimal subtract = tuikuanAllMoney.subtract(discountAmount);
                userDTO.setUserPurse(String.valueOf(subtract.add(userPurse1)));
                //1.1用户总消费金额回滚金额
                BigDecimal totalPrice = order.getTotalPrice();
                userDTO.setUserConsumeAmount(userDTO.getUserConsumeAmount().subtract(totalPrice));
                ResponseData<?> responseData = userFeign.UpdateUser(userDTO);
                // 2.加商品库存
                Integer productFailNum = 0;
                for (ZyShouhoudetail shouhoudetail : shouhoudetailList) {
                    String productId = shouhoudetail.getShdProductid();
                    ZyProduct product = productFeign.selectProduct(productId).get(0);
                    Integer num = shouhoudetail.getShdThnum();
                    ShouhouProductDto shouhouProductDto = new ShouhouProductDto();
                    shouhouProductDto.setId(product.getId());
                    shouhouProductDto.setStock(product.getStock() + num);
                    boolean b1 = productFeign.saveProduct(shouhouProductDto);
                    if (!b1) {
                        productFailNum += 1;
                    }
                }
                if (productFailNum == 0) {
                    //全部订单的库存都回滚成功
                    // 3.订单状态改成5已取消,两个订单的状态都要改
                    ZyOrder order1 = orderService.getById(orderId);
                    order1.setState(5);
                    boolean b1 = orderService.updateById(order1);
                    if (b1) {
                        boolean b2 = ecssOrderFeign.shouhouChangeOrderStatus(orderId);
                        if (b2) {
                            return new ResponseData<>().success();
                        } else {
                            return new ResponseData<>().fail();
                        }
                    } else {
                        //回滚小程序订单失败
                        return new ResponseData<>().fail();
                    }
                }
            }
        }
        //添加售后失败
        return new ResponseData<>().fail();


    }

    @Override
    public ResponseData<?> queryShouhou(PageParam<ShouhouDto> pageParam) {
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        List<ShouhouDto> shouhouDtos = shouhouMapper.queryShouhou(pageParam.getParam());
        PageInfo pageInfo = new PageInfo(shouhouDtos);
        return new ResponseData<>().success(pageInfo);
    }

    @Override
    public ResponseData<?> shenhe(ZyShouhou shouhou) {
        //审核通过，售后表状态改成3：待退货
        shouhou.setShStatus(3);
        boolean b = saveOrUpdate(shouhou);
        if (b) {
            return new ResponseData<>().success();
        } else {
            return new ResponseData<>().fail();
        }
    }

    @Override
    public ResponseData<?> tuikuan(List<ZyShouhou> shouhouList) {
        //主要业务：给用户退款、用户消费金额减去、商品数量（质量问题不回滚）、
        // 售后list 5 状态都改成6



        //根据售后的id查出售后表
        //根据售后表中的订单id查出售后list
        //从售后list筛选出状态为待退款（5）
        String orderId = null;
        ArrayList<ZyShouhou> zyShouhouArrayList= new ArrayList<>();
        for (ZyShouhou shouhou : shouhouList) {
            orderId=shouhou.getOid();
            if (shouhou.getShStatus()==5) {
                //含订单id的所有待退款的售后单
                zyShouhouArrayList.add(shouhou);
            }
        }

        for (ZyShouhou shouhou : zyShouhouArrayList) {
            //改变这些售后状态，改成已完成
            shouhou.setShStatus(6);
        }
        boolean b1 = updateBatchById(zyShouhouArrayList);

        ZyOrder order = orderService.getById(orderId);
        //订单实际付款
        BigDecimal actualAmount = order.getActualAmount();
        //订单优惠金额
        BigDecimal discountAmount = order.getDiscountAmount();
        String userId = order.getUserId();
        UserDTO userDTO = userFeign.queryUserById(userId).getData();
        String userPurse = userDTO.getUserPurse();
        BigDecimal purse = new BigDecimal(userPurse);
        userDTO.setUserPurse(String.valueOf(purse.add(actualAmount)));
        //用户表消费金额总共要减去 订单实付+订单优惠
        BigDecimal all=actualAmount.add(discountAmount);
        userDTO.setUserConsumeAmount(userDTO.getUserConsumeAmount().subtract(all));
        ResponseData<?> responseData = userFeign.UpdateUser(userDTO);

        if (responseData.getCode() == 200) {
                return new ResponseData<>().success();
        }
        return new ResponseData<>().fail();
    }

    @Override
    public ResponseData<?> isGoingToShouhou() {
        Integer number = shouhouMapper.isGoingToShouhou();
        return new ResponseData<>().success(number);
    }

    @SneakyThrows
    @Override
    public ResponseData<?> gukeFahuo(String id) {
        //顾客端（APP）点击发货1.新增物流表  2.售后表状态改为4已退货
        ZyShouhou shouhou = getById(id);
        //顾客点击已发货，售后状态改为5.待退款
        String orderId = shouhou.getOid();

        shouhou.setShStatus(5);
        boolean b = updateById(shouhou);
        if (b) {
            //顾客发货成功
            return new ResponseData<>().success();
        } else {
            return new ResponseData<>().fail();
        }

    }

    @SneakyThrows
    @Override
    public ResponseData<?> addShouhouForYiwancheng(ZyShouhou shouhou1) {
        String orderId = shouhou1.getId();
        String shReason = shouhou1.getShReason();
        String shRemark = shouhou1.getShRemark();
        //String orderId = shouhou.getOid();
        Cookie[] cookies = request.getCookies();
        String jwt = null;
        ZyOrder order = orderService.getById(orderId);
        //订单状态改为已取消
        order.setState(5);
        orderService.updateById(order);
        ecssOrderFeign.shouhouChangeOrderStatus(orderId);
        //订单优惠金额（退款金额=订单总价-订单优惠金额
        BigDecimal discountAmount = order.getDiscountAmount();
        BigDecimal tuikuanAllMoney = new BigDecimal(0);
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("jwt")) {
                jwt = cookie.getValue();
            }
        }
        Map<String, Object> user = JWTUtil.getUserInfo(jwt);
        String userId = user.get("id").toString();
        List<ZyShouhou> shouhouList = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderId).list();
        for (OrderDetail orderDetail : orderDetailList) {
            String shouhouId = String.valueOf(IdUtil.getSnowflake().nextId());
            ZyShouhou shouhou = new ZyShouhou();
            shouhou.setId(shouhouId);
            shouhou.setOid(orderId);
            shouhou.setShOdid(orderDetail.getId());
            shouhou.setShUserid(userId);

            shouhou.setShProductid(orderDetail.getProductId());
            shouhou.setProductName(orderDetail.getProductName());
            BigDecimal orderPrice = orderDetail.getProductPrice().multiply(BigDecimal.valueOf(orderDetail.getBuyNum()));
            shouhou.setOrderAllmoney(orderPrice);
            shouhou.setTuikuanMoney(orderPrice);
            shouhou.setShReason(shReason);
            shouhou.setShShtype("2");
            shouhou.setShStatus(1);

            //shouhou.setFromWhere();
            //shouhou.setToWhere();
            //shouhou.setWuliuId();
            shouhou.setShCreatetime(new Date());
            shouhou.setShRemark(shRemark);
            tuikuanAllMoney = orderPrice.add(tuikuanAllMoney);
            shouhouList.add(shouhou);
        }
        //批量添加售后
        boolean b = saveBatch(shouhouList);
        List<ZyShouhoudetail> shouhoudetailList = new ArrayList<>();
        //售后添加成功  开始添加售后详情
        for (ZyShouhou shouhou : shouhouList) {
            String shouhouDetailId = String.valueOf(IdUtil.getSnowflake().nextId());
            String shouhouId = shouhou.getId();
            ZyShouhoudetail zyShouhoudetail = new ZyShouhoudetail();
            zyShouhoudetail.setId(shouhouDetailId);
            zyShouhoudetail.setShdShid(shouhouId);
            zyShouhoudetail.setShdShtype("2");
            zyShouhoudetail.setShdProductid(shouhou.getShProductid());
            zyShouhoudetail.setShdName(shouhou.getProductName());
            String orderDetailId = shouhou.getShOdid();
            OrderDetail orderDetail = orderDetailService.getById(orderDetailId);
            Integer buyNum = orderDetail.getBuyNum();
            zyShouhoudetail.setShdThnum(buyNum);
            zyShouhoudetail.setShdThprice(shouhou.getTuikuanMoney());
            zyShouhoudetail.setShdRemarks(shRemark);
            //zyShouhoudetail.setShdThpz();
            zyShouhoudetail.setShdThsubmittime(new Date());

            shouhoudetailList.add(zyShouhoudetail);

        }
        boolean aaa = shouhoudetailService.saveBatch(shouhoudetailList);
       if (b && aaa) {
           return new ResponseData<>().success();

       }else {
           return new ResponseData<>().fail();
       }
    }

    @Override
    public ResponseData<?> queryShouhouInKefu(PageParam<?> param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<ShouhouDto> orderBreakDtos = shouhouMapper.queryShouhouInKefu(param.getParam());
        PageInfo objectPageInfo = new PageInfo<>(orderBreakDtos);
        return new ResponseData().success(objectPageInfo);
    }


}




